<template>
    <div class="info-collect">
        <Crumb name="Sparepart Quotation"/>
        <div class="content">
            <el-button
                    type="primary"
                    @click="openAdd()"
            >Add New Quotation
            </el-button>
            <Search>
                <el-input
                        v-model="key"
                        size="small"
                        class="input"
                        placeholder="Search By Quotation No"
                        prefix-icon="el-icon-search"
                />
                <el-button
                        size="small"
                        type="primary"
                >Search
                </el-button>
            </Search>
            <div class="table-wrapper">
                <el-table
                        :data="quotationList.slice((pageNum-1)*pageSize,pageNum*pageSize)"
                        border
                        stripe
                        style="width: 100%">
                    <el-table-column
                            prop="quotationNo"
                            label="Quotation Number"
                            width="180"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="quotationDate"
                            label="Quotation Date"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="quotationBy"
                            label="Request By"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="customer"
                            label="Customer"
                            width="250">
                    </el-table-column>
                    <el-table-column
                            prop="statusDesc"
                            label="Status"
                            width="150">
                    </el-table-column>
                    <el-table-column label="Opr">
                        <template slot-scope="scope">
                            <el-button
                                    size="mini"
                                    @click="openEdit(scope.row)">Detail
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"/>
                </div>

            </div>

            <div class="modal-wrapper">
                <el-dialog
                        title="Sparepart Quotation"
                        :visible.sync="dialogVisible"
                        width="80%"
                        top="0px"
                >
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm"
                             :inline="true">
                        <el-form-item label="Request No." prop="quotationNo">
                            <el-input class="input" v-model="ruleForm.quotationNo"/>
                        </el-form-item>
                        <el-form-item label="Request Date" prop="quotationDate">
                            <el-date-picker class="input" v-model="ruleForm.quotationDate"
                                            value-format="yyyy-MM-dd"/>
                        </el-form-item>
                        <el-form-item label="Request By" prop="quotationBy">
                            <el-select class="input" v-model="ruleForm.quotationBy">
                                <el-option :value="item.id" :key="item.id" v-for="item in employeeList"
                                           :label="item.employeeName"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="Customer" prop="customer">
                            <el-select class="input" v-model="ruleForm.customer" filterable @change="customerChange">
                                <el-option :value="item.customerId" :key="item.customerId" v-for="item in customerList"
                                           :label="item.customerName"/>
                            </el-select>
                        </el-form-item>
                        <div v-show="addressList.length">
                            <el-form-item label="Address">
                                <el-select class="input" v-model="ruleForm.address" placeholder=""
                                           @change="addressChange">
                                    <el-option :value="item.addressId" :key="key" :label="item.addressAbbr"
                                               v-for="(item,key) in addressList"/>
                                </el-select>
                            </el-form-item>
                            <!--地址-->
                            <el-form-item label="Service Address">
                                <el-input class="input" v-model="ruleForm.addressStr"></el-input>
                            </el-form-item>
                        </div>
                        <div v-show="contactList.length">
                            <el-form-item label="contact">
                                <el-select class="input" v-model="ruleForm.contact" placeholder="Contact Name"
                                           @change="contactNameChange">
                                    <el-option :value="contact.contactId" :key="contact.id" :label="contact.contactName"
                                               v-for="(contact) in contactList"/>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="Phone Number">
                                <el-select v-model="ruleForm.phone" size="small" class="input">
                                    <el-option
                                            v-for="item in contactPhoneList"
                                            :key="item.id"
                                            :label="item.phone"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                    </el-form>
                    <div class="items">
                        <el-button size="small" type="primary" @click="showDB">Add Items</el-button>
                        <el-button size="small" type="primary">Package</el-button>
                        <el-button size="small" type="primary">Add Service</el-button>
                        <el-select v-model="priceFactor" size="small" class="input" style="margin-left: 20px;"
                                   placeholder="Sale Prcie Factor Default is 1">
                            <el-option label="A" :value="1.05"></el-option>
                            <el-option label="B" :value="1.15"></el-option>
                            <el-option label="C" :value="1.2"></el-option>
                            <el-option label="D" :value="1.3"></el-option>
                            <el-option label="E" :value="0"></el-option>
                        </el-select>
                        <el-currency-input style="display: inline-block;width: 200px" v-model="currency"
                                           placeholder="Curreny" :type="10"></el-currency-input>
                        <div class="table">
                            <Data-base @deleteItem="deleteItem" :partList="partList" :price-edit="true"/>
                        </div>
                        <div class="discount" style="text-align: right;">
                            <div style="margin: 10px 0">
                                2.Discount:
                                <el-input v-model="ruleForm.discount" size="small" class="input"
                                          placeholder="Discount"></el-input>
                                %
                            </div>
                            <div>
                                3.PPN:
                                <el-input v-model="ruleForm.ppn" disabled size="small" class="input"
                                          placeholder="10%"></el-input>
                                %
                            </div>
                        </div>

                        <div>
                            4.Shipment:
                            <el-select v-model="ruleForm.shipment" size="small" class="input">
                                <el-option label="pick up" :value=0></el-option>
                                <el-option label="Delivery" :value=1></el-option>
                                <el-option label="Logistic" :value=2></el-option>
                                <el-option label="Exclude shipment fee" :value=3></el-option>
                            </el-select>
                            <el-input v-model="ruleForm.shipmentFee" class="input" size="small"
                                      placeholder="Shipment Fee"></el-input>
                        </div>
                        <div>
                            5.Total: {{totalPrice}}
                        </div>
                    </div>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                        <el-button type="warning" @click="saveForm">Save</el-button>
                        <el-button type="info" @click="print">Print</el-button>
                        <el-button type="primary" @click="confirmPo">convert SO</el-button>
                    </span>
                </el-dialog>
                <Part-item @close="dbVisible = false" @add="add" :visible="dbVisible" :show-all="true"
                />
                <el-dialog
                        title="Customer Po"
                        :visible.sync="poShow"
                        width="30%"
                >
                    <div>
                        Customer Po:
                        <el-input v-model="ruleForm.customerPo" placeholder="PO" class="my-input"
                                  size="small"></el-input>
                    </div>
                    <span slot="footer" class="dialog-footer">
                    <el-button @click="submitForm">Skip</el-button>
                    <el-button type="primary" @click="submitForm">Confirm</el-button>
                  </span>
                </el-dialog>

            </div>
        </div>
    </div>
</template>

<script>
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import DataBase from '@/components/part/spDataBase'
    import PartItem from '@/components/part/sparePartItem'
    import {getCustomerAddress, getCustomerContact, customerContactPhone} from "../../api/service";
    import {
        getQuotationList,
        getQuotationNo,
        getQuotationDetail,
        saveQuotation,
        confirmQuotation
    } from "../../api/quotation";
    import {mapActions, mapGetters} from 'vuex'
    import {ERROR_OK} from "../../util/config";
    import dbMixins from '../../util/spMixins'
    import mixins from '../../util/mixins'
    import {money} from "../../util";

    export default {
        name: "part-quotation",
        mixins: [dbMixins, mixins],
        data() {
            return {
                list: [],
                addressList: [],
                contactList: [],
                contactPhoneList: [],
                priceFactor: 1.05,
                currency: 1,

                ruleForm: {
                    quotationNo: '',
                    quotationDate: '',
                    quotationBy: '',
                    customer: '',
                    status: '',
                    address: '',
                    addressStr: '',
                    contact: '',
                    phone: '',
                    serviceId: '',
                    discount: '',
                    ppn: 10,
                    shipment: '',
                    shipmentFee: '',
                    price: '',
                    customerPo: ''
                },
                rules: {
                    quotationNo: [
                        {required: true, message: 'Quotation No is required', trigger: 'blur'},
                    ],
                    quotationBy: [
                        {required: true, message: 'Quotation By is required', trigger: 'change'},
                    ],
                    customer: [
                        {required: true, message: 'Name is required', trigger: 'change'}
                    ],
                    quotationDate: [
                        {required: false}
                    ]
                },
                key: '',
                dialogVisible: false,
                poShow: false
            }
        },
        computed: {
            ...mapGetters(['customerList', 'employeeList']),
            factor() {
                if (this.priceFactor && this.currency) {
                    return (this.priceFactor * 100) * (this.currency * 100) / 10000;
                } else {
                    return 0
                }
            },
            quotationList() {
                return this.list.filter(quotation => quotation.quotationNo.indexOf(this.key) > -1)
            },
            totalPrice() {
                let total = 0;
                const discount = ((100 - (this.ruleForm.discount ? this.ruleForm.discount : 0)) / 100);
                const ppn = 1.1;
                const shipment = this.ruleForm.shipmentFee ? parseInt(this.ruleForm.shipmentFee) : 0;
                if (this.partList.length) {
                    this.partList.forEach(item => {
                        total += parseFloat(item.salesPrice || 0) * item.number;
                    });
                    total = total * discount * ppn + shipment;
                    total = total.toFixed(2);
                    return total
                } else {
                    return total
                }
            }
        },
        mounted() {
            this.$nextTick(() => { //异步加载pdf模块
                import('../../util/pdf.js').then(model => {
                    this.pdf = model.default;
                })
            })
        },
        methods: {
            print() {
                if (!this.pdf) {
                    this.$notify.warning('PDF Creator is not ready,Pls wait for a moment');
                    return
                }
                if (!this.ruleForm.id) {
                    this.$notify.warning('Please confirm or save first');
                    return
                }
                let body = [
                    [
                        {text: 'No', alignment: 'center'},
                        {text: 'Part No', alignment: 'center'},
                        {text: 'description', colSpan: 2, style: 'tableHeader', alignment: 'center'},
                        {},
                        {text: 'Rate', style: 'tableHeader', alignment: 'center'},
                        {text: 'Qty', colSpan: 2, style: 'tableHeader', alignment: 'center'},
                        {},
                        {text: 'Line Total', style: 'tableHeader', alignment: 'center'},
                    ],
                    [
                        {text: '序号', style: 'tableHeader', alignment: 'center'},
                        {text: '配件编号', style: 'tableHeader', alignment: 'center'},
                        {text: '中文描述', style: 'tableHeader', alignment: 'center'},
                        {text: '英文描述', style: 'tableHeader', alignment: 'center'},
                        {text: '单价', style: 'tableHeader', alignment: 'center'},
                        {text: '数量', style: 'tableHeader', alignment: 'center'},
                        {text: '单位', style: 'tableHeader', alignment: 'center'},
                        {text: '总计', style: 'tableHeader', alignment: 'center'}
                    ],
                ];
                const mainBody = this.partList.map((item, index) => {
                    return [index + 1, item.partsNumber, item.denomination, item.designation, money(item.salesPrice), item.number, 'pc', money(item.salesPrice * item.number)]
                });
                body = body.concat(mainBody);
                body = [...body, [{
                    text: 'Service Item',
                    colSpan: 4,
                    style: 'tableHeader',
                    alignment: 'left'
                }, {}, {}, {}, {text: 'Service Fee', colSpan: 4, style: 'tableHeader', alignment: 'left'}, {}, {}, {}],
                    [{
                        text: 'Shipment: ' + this.ruleForm.shipmentDesc,
                        colSpan: 4,
                        style: 'tableHeader',
                        alignment: 'left'
                    },
                        {}, {}, {},
                        {
                            text: 'Shipment Fee: ' + this.ruleForm.shipmentFee,
                            colSpan: 4,
                            style: 'tableHeader',
                            alignment: 'left'
                        }, {}, {}, {}]];
                let total = 0;
                this.partList.forEach(item => {
                    total += item.salesPrice * item.number
                });

                let doc = {
                    filename: 'QO',
                    pageSize: 'LEGAL',
                    pageMargins: [10, 200, 10, 60],
                    header: [
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '70%',
                                    text: [
                                        {
                                            text: 'PT INDONESIA EQUIPMENT CENTRE\n',
                                            style: 'header'
                                        },
                                        {
                                            text: "Leading in Service Innovation\n",
                                            style: 'subTitle'
                                        },
                                        ' No.17-18 Blok A, Ruko Inkopal Kelapa Gading \n',
                                        ' Jl. Boulevard Barat Raya Jakarta Utara 14240 Indonesia \n',
                                        ' Tel: 0800-1581212'
                                    ],

                                },
                                {
                                    width: '*',
                                    text: 'Quotation',
                                    style: 'title',
                                    alignment: 'right'
                                }
                            ],
                        },
                        {
                            margin: [20, -10, 0, 20],
                            columns: [
                                {
                                    width: 50,
                                    text: 'Bill To:'
                                },
                                {
                                    width: '60%',
                                    text: [
                                        `Customer: ${this.ruleForm.customerName}\n`,
                                        `Address: ${this.ruleForm.addressStr}\n`,
                                        `Contact Person : ${this.ruleForm.contactName}\n`,
                                        `Contact Number: ${this.ruleForm.phoneNumber}`
                                    ]
                                },
                                {
                                    width: '*',
                                    text: [
                                        `Date: ${this.ruleForm.quotationDate}\n`,
                                        'Payment: COD'
                                    ]
                                }
                            ]
                        }
                    ],
                    content: [
                        {
                            layout: 'lightHorizontalLines',
                            alignment: 'center',
                            table: {
                                widths: ['auto', 'auto', 90, 120, 'auto', 'auto', 'auto', 140],
                                headerRows: 2,
                                // keepWithHeaderRows: 1,
                                body: body
                            }
                        },
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '50%',
                                    text: [
                                        ' Make all checks payable to\n',
                                        'A/N: PT. INDONESIA EQUIPMENT CENTRE\n',
                                        'NO.: 100000900155030\n',
                                        'BANK OF CHINA (HONG KONG) LIMITED'
                                    ]
                                },
                                {
                                    width: '*',
                                    text: [
                                        `Sub Total: ${money(total)}\n`,
                                        // `Discount: ${this.ruleForm.discount}\n`,
                                        // `Total After Discount: ${money(total * ((100 - this.ruleForm.discount) / 100))}\n`,
                                        `PPN: ${this.ruleForm.ppn}%\n`,
                                        {
                                            text: 'Total Inc PPN ' + money(this.totalPrice),
                                            alignment: 'center',
                                            style: {
                                                background: '#ddd'
                                            }
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    footer: [
                        {
                            text: 'If you have any questions or concerns, please contact 0800-1581212',
                            width: '100%',
                            alignment: 'center'
                        },
                        {text: 'THANK YOU FOR YOUR BUSINESS! ', width: '100%', alignment: 'center'}
                    ],

                    defaultStyle: {
                        font: 'msyh',
                        fontSize: 9,
                    },

                    styles: {
                        header: {
                            fontSize: 15,
                            bold: true
                        },
                        title: {
                            fontWeight: 'light',
                            fontSize: 25,
                            bold: false
                        },
                        subTitle: {
                            fontSize: 12,
                            bold: true,
                            italic: true
                        }
                    }

                }
                this.pdf.open(doc);
            },
            confirmPo() {
                this.poShow = true;
            },
            showDB() {
                this.dbVisible = true
            },
            async contactNameChange(contactId) {
                const {status, data} = await customerContactPhone(contactId);
                if (status === ERROR_OK) {
                    this.contactPhoneList = data
                }
            },
            addressChange(id) {
                if (id) {
                    const target = this.addressList.find(item => item.addressId === id);
                    this.ruleForm.addressStr = target.address;
                }
            },
            customerChange(id) {
                if (id) {
                    this.getAddress(id);
                    this.getContact(id);
                    this.getCustomerLevel(id);
                }
            },
            getCustomerLevel(id){
               const target =  this.customerList.find(item => item.customerId === id);
               const level = target.customerLevel;
               const levelList = {
                   "A":1.05,
                   "B":1.15,
                   "C":1.2,
                   "D":1.3,
               };
               this.priceFactor = levelList[level] || 0;


            },
            async getAddress(customerId) {
                const {status, data} = await getCustomerAddress(customerId);
                if (status === ERROR_OK) {
                    this.addressList = data;
                } else {
                    this.addressList = []
                }
            },
            async getContact(customerId) {
                const {status, data} = await getCustomerContact(customerId);
                if (status === ERROR_OK) {
                    this.contactList = data;
                } else {
                    this.contactList = [];
                }
            },
            async saveForm() {
                this.$refs.ruleForm.validate(async valid => {
                    if (valid) {
                        const quotationDetail = JSON.stringify(this.partList.map(item => {
                            return {partId: item.id, quantity: item.number}
                        }));
                        const {
                            id,
                            quotationNo,
                            quotationBy,
                            quotationDate,
                            customer,
                            contact,
                            address,
                            discount,
                            ppn,
                            shipment,
                            shipmentFee,
                            phone
                        } = this.ruleForm;
                        let {status, msg} = await saveQuotation({
                            quotationNo,
                            quotationBy,
                            id,
                            customer,
                            quotationDetail,
                            contact,
                            address,
                            discount,
                            ppn,
                            shipment,
                            phone,
                            shipmentFee,
                            quotationDateStr: quotationDate,
                            coefficient: this.factor
                        });
                        if (status === ERROR_OK) {
                            this.$message({
                                message: 'save Successfully',
                                type: 'success'
                            });
                            this._getQuotationList()
                        } else {
                            this.$notify({
                                title: 'Error',
                                message: msg
                            })
                        }
                        this.dialogVisible = false;
                    }
                });
            },
            async submitForm() {
                this.$refs.ruleForm.validate(async valid => {
                    if (valid) {
                        const quotationDetail = JSON.stringify(this.partList.map(item => {
                            return {partId: item.id, quantity: item.number}
                        }));
                        const {quotationNo, quotationBy, quotationDate, customer, contact, address, discount, ppn, shipment, shipmentFee, phone, customerPo, id} = this.ruleForm;
                        let {status, msg} = await confirmQuotation({
                            quotationNo,
                            quotationBy,
                            quotationDate,
                            customer,
                            quotationDetail,
                            contact,
                            address,
                            discount,
                            ppn,
                            shipment,
                            phone,
                            shipmentFee,
                            id,
                            customerPo,
                            quotationDateStr: quotationDate,
                            coefficient: this.factor
                        });
                        if (status === ERROR_OK) {
                            this.$message({
                                message: 'confirm Successfully',
                                type: 'success'
                            });
                            this._getQuotationList()
                        } else {
                            this.$notify({
                                title: 'Error',
                                message: msg
                            })
                        }
                        this.dialogVisible = false;
                        this.poShow = false
                    }
                });
            },
            clear() {
                this.ruleForm = {
                    quotationNo: '',
                    quotationDate: '',
                    quotationBy: '',
                    customer: '',
                    status: '',
                    address: '',
                    addressDesc: '',
                    contact: '',
                    phone: '',
                    serviceId: '',
                    discount: '',
                    ppn: 10,
                    shipment: '',
                    shipmentFee: '',
                    customerPo: ''
                };
                this.partList = []
            },
            openAdd() {
                this.clear();
                this._getQuotationNo();
                this.dialogVisible = true
            },
            async openEdit(r) {
                let {status, data} = await getQuotationDetail(r.id);
                if (status === ERROR_OK) {
                    this.ruleForm = data;
                    this.factor = r.coefficient || 1;  //价格系数默认1
                    if (data.spareQuotationDetailVoList) { //解析配件详情列表
                        this.partList = data.spareQuotationDetailVoList.map(item => {
                            return {
                                ...item,
                                id: item.partId,
                                number: item.quantity,
                                partsNumber: item.partNo,
                                salesPrice: item.unitPrice * this.factor,
                                quantity: item.stockQuantity,
                                originPrice: item.unitPrice
                            }
                        })
                    } else {
                        this.partList = [];
                    }
                    this.dialogVisible = true;
                } else {
                    this.$notify.error('Fail to get Detail')
                }


            },
            async _getQuotationList() {
                let {status, data} = await getQuotationList();
                if (status === ERROR_OK) {
                    this.list = data;
                    this.total = data.length
                }
            },
            async _getQuotationNo() {
                const {status, data} = await getQuotationNo();
                if (status === ERROR_OK) {
                    this.ruleForm.quotationNo = data
                }
            },
            ...mapActions({
                getCustomer: 'loadCustomerList',
                getEmployee: 'loadEmployeeList'
            })
        },
        watch: {
            factor(fact) {
                if (typeof  fact !== 'number') {
                    this.factor = 1.05;
                } else {
                    this.partList.forEach(item => {
                        item.salesPrice = parseFloat(((item.originPrice * 100) * (fact * 100) / 10000).toPrecision(12))
                    })
                }
            },
            partList() {
                this.partList.forEach(item => {
                    item.salesPrice = parseFloat(((item.originPrice * 100) * (this.factor * 100) / 10000).toPrecision(12))
                })
            },
            quotationList(list) {
                this.total = list.length
            },
            'ruleForm.customer': {
                handler: function (customerId) {
                    if (customerId) {
                        this.customerChange(customerId)

                    }
                },
                deep: true
            },
            // 'ruleForm.address':{
            //     handler:function(addressId) {
            //         if(addressId) {
            //             this.addressChange(addressId)
            //         }
            //     }
            // },
            'ruleForm.contact': {
                handler: function (contactId) {
                    if (contactId) {
                        this.contactNameChange(contactId)
                    }
                }
            }
        },
        created() {
            this._getQuotationList();
            this.getCustomer();
            this.getEmployee();
        },
        components: {
            Crumb, Search, DataBase, PartItem
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    .modal-wrapper {
        .input {
            width: 200px;
        }
        .items {
            span {
                display: inline-block;
                width: 140px;
                text-align: right;
                font-size: 16px;
                margin-right: 10px;
            }
            label {
                width: 142px;
                height: 32px;
                display: inline-block;
                text-align: center;
                color: #fff;
                margin-right: 20px;
                cursor: pointer;
                line-height: 32px;
                border-radius: 3px;
                background: #409Eff;
            }
            .table {
                margin-top: 5px;
            }
        }
    }

</style>